package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 同步Cookie、session相关信息
 * @author gcq
 * @Create 2020-11-17
 */
@Configuration
public class GuliFeignConfig {

    /**
     * 设置feign远程调用 同步cookie信息
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 1、RequestContextHolder拿到刚进来的这个请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    // 老请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null) {
                        //同步请求数据，Cookie
                        String cookies = request.getHeader("Cookie");
                        // 给新请求同步了老请求的cookie
                        template.header("Cookie",cookies);
                    }
                }
            }
        };
    }

}